package com.isoft.airportsystem.controller.system;

import com.isoft.airportsystem.common.Result;
import com.isoft.airportsystem.mapper.DfdlMapper;
import com.isoft.airportsystem.mapper.BLLSMapper;
import com.isoft.airportsystem.mapper.DLYEMapper;
import com.isoft.airportsystem.mapper.system.UserMapper;
import com.isoft.airportsystem.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计数据控制器
 */
@RestController
@RequestMapping("/api/system/statistics")
public class StatisticsController {

    @Autowired
    private UserService userService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取平台首页统计数据
     *
     * @param userId 用户ID
     * @return 统计数据
     */
    @GetMapping("/dashboard")
    public Result<Map<String, Object>> getDashboardStatistics(@RequestParam Long userId) {
        // 获取用户权限，根据权限返回不同的统计数据。
        List<String> permissions = userService.selectPermissionsByUserId(userId);

        // 构建返回结果
        Map<String, Object> data = new HashMap<>();

        // 基础统计数据（所有用户都可见）
        // 查询航班总数
        Integer totalFlights = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT", Integer.class);
        data.put("totalFlights", totalFlights != null ? totalFlights : 6813);

        // 查询今日航班数
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Integer todayFlights = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE TO_CHAR(DFLT_FEXD, 'YYYY-MM-DD') = ?",
                new Object[]{today}, Integer.class);
        data.put("todayFlights", todayFlights != null ? todayFlights : 156);

        // 如果没有权限，提供基础数据
        if (permissions.isEmpty()) {
            // 为普通用户提供基础统计数据
            data.put("totalUsers", 1250);
            data.put("activeUsers", 1180);
            data.put("systemStatus", "正常");
            data.put("delayedFlights", 45);
            data.put("canceledFlights", 12);

            // 添加系统资源使用情况
            Map<String, Object> systemResources = new HashMap<>();
            systemResources.put("cpuUsage", 35);
            systemResources.put("memoryUsage", 42);
            systemResources.put("diskUsage", 28);
            data.put("systemResources", systemResources);

            // 添加行李处理统计
            Map<String, Object> baggageStats = new HashMap<>();
            baggageStats.put("totalBaggage", 8920);
            baggageStats.put("mishandledBaggage", 156);
            data.put("baggageStats", baggageStats);

            return Result.success(data);
        }

        // 根据权限添加不同的统计数据
        if (permissions.contains("system:admin")) {
            // 管理员可见的统计数据
            // 查询用户总数
            Integer totalUsers = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM sys_user WHERE del_flag = 0", Integer.class);
            data.put("totalUsers", totalUsers != null ? totalUsers : 1250);

            // 查询活跃用户数（状态为1的用户）
            Integer activeUsers = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM sys_user WHERE status = 1 AND del_flag = 0", Integer.class);
            data.put("activeUsers", activeUsers != null ? activeUsers : 1180);
            data.put("systemStatus", "正常");  // 模拟数据，实际应从系统监控获取

            // 添加系统资源使用情况
            Map<String, Object> systemResources = new HashMap<>();
            systemResources.put("cpuUsage", 35);      // 模拟数据，实际应从系统监控获取
            systemResources.put("memoryUsage", 42);    // 模拟数据，实际应从系统监控获取
            systemResources.put("diskUsage", 28);      // 模拟数据，实际应从系统监控获取
            data.put("systemResources", systemResources);
        }

        if (permissions.contains("system:flight:manage")) {
            // 航班管理人员可见的统计数据
            // 查询延误航班数
            Integer delayedFlights = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM MSG_DFME_DLYE", Integer.class);
            data.put("delayedFlights", delayedFlights != null ? delayedFlights : 45);

            // 查询取消航班数
            Integer canceledFlights = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_STAT = 'CNL'", Integer.class);
            data.put("canceledFlights", canceledFlights != null ? canceledFlights : 12);

            // 添加行李处理统计
            Map<String, Object> baggageStats = new HashMap<>();

            // 查询行李总数
            Integer totalBaggage = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM DFLT_BLLS_BELT", Integer.class);
            baggageStats.put("totalBaggage", totalBaggage != null ? totalBaggage : 8920);

            // 查询处理不当的行李数
            Integer mishandledBaggage = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM DFLT_BLLS_BELT WHERE BTSC != 'NRM' AND BTSC IS NOT NULL", Integer.class);
            baggageStats.put("mishandledBaggage", mishandledBaggage != null ? mishandledBaggage : 156);

            data.put("baggageStats", baggageStats);
        }

        return Result.success(data);
    }

    /**
     * 获取航班统计数据
     *
     * @return 航班统计数据
     */
    @GetMapping("/flights")
    public Result<Map<String, Object>> getFlightStatistics() {
        // 构建返回结果
        Map<String, Object> data = new HashMap<>();

        // 航班状态统计（饼图数据）
        List<Map<String, Object>> flightStatusStats = new ArrayList<>();

        // 查询准点航班数
        Integer onTimeCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_STAT  = 'ONT' OR DFLT_STAT  IS NULL", Integer.class);
        Map<String, Object> onTime = new HashMap<>();
        onTime.put("name", "准点");
        onTime.put("value", onTimeCount != null ? onTimeCount : 5877);
        flightStatusStats.add(onTime);

        // 查询延误航班数
        Integer delayedCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM MSG_DFME_DLYE", Integer.class);
        Map<String, Object> delayed = new HashMap<>();
        delayed.put("name", "延误");
        delayed.put("value", delayedCount != null ? delayedCount : 936);
        flightStatusStats.add(delayed);

        // 查询取消航班数
        Integer canceledCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_STAT = 'CNL'", Integer.class);
        Map<String, Object> canceled = new HashMap<>();
        canceled.put("name", "取消");
        canceled.put("value", canceledCount != null ? canceledCount : 0);
        flightStatusStats.add(canceled);

        // 查询备降航班数
        Integer divertedCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_STAT = 'DIV'", Integer.class);
        Map<String, Object> diverted = new HashMap<>();
        diverted.put("name", "备降");
        diverted.put("value", divertedCount != null ? divertedCount : 0);
        flightStatusStats.add(diverted);

        data.put("flightStatusStats", flightStatusStats);

        // 近7天航班数量统计（折线图数据）- 统计2017年6月1日到6月10日每天的真实数据
        Map<String, Object> weeklyFlightStats = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> flightCounts = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.of(2017, 6, 1);
        LocalDate end = LocalDate.of(2017, 6, 10);
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            dates.add(dateStr);
            // 查询当天的航班数
            Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE TO_CHAR(DFLT_FEXD, 'YYYY-MM-DD') = ?",
                    new Object[]{dateStr}, Integer.class);
            flightCounts.add(count != null ? count : 0);
        }
        weeklyFlightStats.put("dates", dates);
        weeklyFlightStats.put("counts", flightCounts);
        data.put("weeklyFlightStats", weeklyFlightStats);

        // 航班类型统计（柱状图数据）
        Map<String, Object> flightTypeStats = new HashMap<>();
        List<String> types = List.of("国内航班", "国际航班", "地区航班");
        List<Integer> typeCounts = new ArrayList<>();

        // 查询国内航班数量
        Integer domesticCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_FLIO = 'D'", Integer.class);
        typeCounts.add(domesticCount != null ? domesticCount : 5234);

        // 查询国际航班数量
        Integer internationalCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_FLIO = 'I'", Integer.class);
        typeCounts.add(internationalCount != null ? internationalCount : 1579);

        // 查询地区航班数量
        Integer regionalCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFOE_DFDL_DFLT WHERE DFLT_FLIO = 'R'", Integer.class);
        typeCounts.add(regionalCount != null ? regionalCount : 0);

        flightTypeStats.put("types", types);
        flightTypeStats.put("counts", typeCounts);
        data.put("flightTypeStats", flightTypeStats);

        return Result.success(data);
    }

    /**
     * 获取行李统计数据
     *
     * @return 行李统计数据
     */
    @GetMapping("/baggage")
    public Result<Map<String, Object>> getBaggageStatistics() {
        // 构建返回结果
        Map<String, Object> data = new HashMap<>();

        // 行李处理状态统计（饼图数据）
        List<Map<String, Object>> baggageStatusStats = new ArrayList<>();

        // 查询正常行李数量
        Integer normalCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFLT_BLLS_BELT WHERE BTSC = 'NRM' OR BTSC IS NULL", Integer.class);
        Map<String, Object> normal = new HashMap<>();
        normal.put("name", "正常");
        normal.put("value", normalCount != null ? normalCount : 8764);
        baggageStatusStats.add(normal);

        // 查询延误行李数量
        Integer delayedCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFLT_BLLS_BELT WHERE BTSC = 'DLY'", Integer.class);
        Map<String, Object> delayed = new HashMap<>();
        delayed.put("name", "延误");
        delayed.put("value", delayedCount != null ? delayedCount : 156);
        baggageStatusStats.add(delayed);

        // 查询损坏行李数量
        Integer damagedCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM DFLT_BLLS_BELT WHERE BTSC = 'DMG'", Integer.class);
        Map<String, Object> damaged = new HashMap<>();
        damaged.put("name", "损坏");
        damaged.put("value", damagedCount != null ? damagedCount : 0);
        baggageStatusStats.add(damaged);

        data.put("baggageStatusStats", baggageStatusStats);

        // 近7天行李处理数量统计（折线图数据）- 统计2017年6月1日到6月10日每天的真实数据
        Map<String, Object> weeklyBaggageStats = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> baggageCounts = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.of(2017, 6, 1);
        LocalDate end = LocalDate.of(2017, 6, 10);
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            dates.add(dateStr);
            // 查询当天的行李数
            Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM DFLT_BLLS_BELT WHERE TO_CHAR(RSTR, 'YYYY-MM-DD') = ?",
                    new Object[]{dateStr}, Integer.class);
            baggageCounts.add(count != null ? count : 0);
        }
        weeklyBaggageStats.put("dates", dates);
        weeklyBaggageStats.put("counts", baggageCounts);
        data.put("weeklyBaggageStats", weeklyBaggageStats);

        return Result.success(data);
    }
}